package org.lc.stk.web.dto.user;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import org.lc.stk.model.user.Role;
import org.lc.stk.model.user.User;
import org.lc.stk.model.user.UserRole;

import java.util.Set;
import java.util.stream.Collectors;

@Data
@Schema(description = "用户管理响应")
public class UserAdminResponse {

    @Schema(description = "用户ID")
    private Integer id;

    @Schema(description = "用户名")
    private String username;

    @Schema(description = "姓名")
    private String name;

    @Schema(description = "邮箱")
    private String email;

    @Schema(description = "部门ID")
    private Integer departmentId;

    @Schema(description = "部门名称")
    private String departmentName;

    @Schema(description = "用户类型（student/teacher）")
    private String userType;

    @Schema(description = "状态(0:禁用 1:启用)")
    private Integer state;

    @Schema(description = "是否已删除")
    private Boolean deleted;

    @Schema(description = "角色列表")
    private Set<RoleInfo> roles;

    @Data
    @Schema(description = "角色信息")
    public static class RoleInfo {
        @Schema(description = "角色ID")
        private Integer id;

        @Schema(description = "角色代码")
        private String code;

        @Schema(description = "角色名称")
        private String name;

        @Schema(description = "角色描述")
        private String description;

        @Schema(description = "是否系统内置")
        private Boolean isSystem;

        @Schema(description = "是否启用")
        private Boolean enabled;
    }

    public static UserAdminResponse fromUser(User user) {
        UserAdminResponse response = new UserAdminResponse();
        response.setId(user.getId());
        response.setUsername(user.getUsername());
        response.setName(user.getName());
        response.setEmail(user.getEmail());
        response.setDepartmentId(user.getDepartment().getId());
        response.setDepartmentName(user.getDepartment().getName());
        response.setUserType(user instanceof org.lc.stk.model.user.Student ? "student" : "teacher");
        response.setState(user.getState());
        response.setDeleted(user.getDeleted());
        
        response.setRoles(user.getRoles().stream()
                .map(UserRole::getRole)
                .map(role -> {
                    RoleInfo roleInfo = new RoleInfo();
                    roleInfo.setId(role.getId());
                    roleInfo.setCode(role.getCode());
                    roleInfo.setName(role.getName());
                    roleInfo.setDescription(role.getDescription());
                    roleInfo.setIsSystem(role.getIsSystem());
                    roleInfo.setEnabled(role.getEnabled());
                    return roleInfo;
                })
                .collect(Collectors.toSet()));
        
        return response;
    }
}